package chatgpt3_5

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"zy_bot_demo/viper"
)

// 代理
var Transport *http.Transport
var apiUrl = "https://api.openai.com/v1/chat/completions"
var method = "POST"

// 这里填写你的openai api key
//var apiKey = "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"
//var chatGptModel = "gpt-3.5-turbo"

func SendMessage(content string) (*Resp, error) {
	println("start....")
	println("问题....：" + content)
	// 设置代理服务器的地址
	proxyUrl, err := url.Parse("http://127.0.0.1:7890")
	if err != nil {
		panic(err)
		println(err)
	}

	// 创建一个HTTP Transport
	Transport = &http.Transport{
		Proxy: http.ProxyURL(proxyUrl),
	}
	messageReq := MessageReq{
		Model: viper.Config.ChatGpt.ChatGptModel,
		Messages: []Message{
			{
				Role:    "user",
				Content: content,
			},
		},
	}
	marshal, err2 := json.Marshal(messageReq)
	if err2 != nil {
		panic(err2)
	}
	client := &http.Client{}
	req, err := http.NewRequest(method, apiUrl, bytes.NewReader(marshal))
	//// 设置HTTP客户端的Transport
	client.Transport = Transport
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	req.Header.Add("Content-Type", "application/json")
	//req.Header.Add("Authorization", "Bearer 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")
	//req.Header.Add("Authorization", "Bearer "+viper.Config.ChatGpt.ApiKey)
	req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", viper.Config.ChatGpt.ApiKey))

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	var c = &Resp{}
	json.Unmarshal(body, c)
	fmt.Println(string(body))
	println("end.....")

	return c, nil
}
